from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_stock.dao.monthly_dao import MonthlyDao
from module_stock.entity.vo.monthly_vo import DeleteMonthlyModel, MonthlyModel, MonthlyPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class MonthlyService:
    """
    股票月线模块服务层
    """

    @classmethod
    async def get_monthly_list_services(
        cls, query_db: AsyncSession, query_object: MonthlyPageQueryModel, is_page: bool = False
    ):
        """
        获取股票月线列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 股票月线列表信息对象
        """
        monthly_list_result = await MonthlyDao.get_monthly_list(query_db, query_object, is_page)

        return monthly_list_result

    @classmethod
    async def get_all_monthly_services(
        cls, query_db: AsyncSession, symbol: str
    ):
        """
        获取所有股票月线service

        :param query_db: orm对象
        :param symbol: 股票代码
        :return: 股票月线列表
        """
        monthly_list_result = await MonthlyDao.get_all_monthly(query_db, symbol)

        return CamelCaseUtil.transform_result(monthly_list_result)


    @classmethod
    async def add_monthly_services(cls, query_db: AsyncSession, page_object: MonthlyModel):
        """
        新增股票月线信息service

        :param query_db: orm对象
        :param page_object: 新增股票月线对象
        :return: 新增股票月线校验结果
        """
        try:
            await MonthlyDao.add_monthly_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_monthly_services(cls, query_db: AsyncSession, page_object: MonthlyModel):
        """
        编辑股票月线信息service

        :param query_db: orm对象
        :param page_object: 编辑股票月线对象
        :return: 编辑股票月线校验结果
        """
        edit_monthly = page_object.model_dump(exclude_unset=True, exclude={'create_time', })
        monthly_info = await cls.monthly_detail_services(query_db, page_object.id)
        if monthly_info.id:
            try:
                await MonthlyDao.edit_monthly_dao(query_db, edit_monthly)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='股票月线不存在')

    @classmethod
    async def delete_monthly_services(cls, query_db: AsyncSession, page_object: DeleteMonthlyModel):
        """
        删除股票月线信息service

        :param query_db: orm对象
        :param page_object: 删除股票月线对象
        :return: 删除股票月线校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for id in id_list:
                    await MonthlyDao.delete_monthly_dao(query_db, MonthlyModel(id=id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入id为空')

    @classmethod
    async def monthly_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取股票月线详细信息service

        :param query_db: orm对象
        :param id: id
        :return: id对应的信息
        """
        monthly = await MonthlyDao.get_monthly_detail_by_id(query_db, id=id)
        if monthly:
            result = MonthlyModel(**CamelCaseUtil.transform_result(monthly))
        else:
            result = MonthlyModel(**dict())

        return result

    @staticmethod
    async def export_monthly_list_services(monthly_list: List):
        """
        导出股票月线信息service

        :param monthly_list: 股票月线信息列表
        :return: 股票月线信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'id': 'id',
            'tradeDate': '交易日期',
            'symbol': '股票代码',
            'open': '开盘价',
            'close': '收盘价',
            'high': '最高价',
            'low': '最低价',
            'vol': '成交量',
            'amount': '成交额',
            'amplitude': '振幅',
            'pctChg': '涨跌幅',
            'chg': '涨跌额',
            'turn': '换手率',
            'createTime': '创建时间',
            'updateTime': '更新时间',
        }
        binary_data = ExcelUtil.export_list2excel(monthly_list, mapping_dict)

        return binary_data
